<template>
  <div class="dept-management">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        ref="queryFormRef"
        :model="queryForm"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="deptName">
          <el-input
            v-model="queryForm.deptName"
            placeholder="请输入部门名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryForm.status"
            placeholder="部门状态"
            clearable
            style="width: 200px"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">
            搜索
          </el-button>
          <el-button icon="Refresh" @click="resetQuery">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <div class="operation-bar">
        <div class="left-operations">
          <el-button
            v-permission="['system:dept:add']"
            type="primary"
            icon="Plus"
            @click="handleAdd"
          >
            新增
          </el-button>
          <el-button type="info" icon="Sort" @click="toggleExpandAll">
            展开/折叠
          </el-button>
        </div>
        <div class="right-operations">
          <el-tooltip content="刷新" placement="top">
            <el-button icon="Refresh" circle @click="getList" />
          </el-tooltip>
        </div>
      </div>

      <!-- 部门列表 -->
      <el-table
        v-loading="loading"
        :data="deptList"
        row-key="deptId"
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column prop="deptName" label="部门名称" width="260" />
        <el-table-column prop="orderNum" label="排序" width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <dict-tag :options="statusOptions" :value="row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="200">
          <template #default="{ row }">
            <span>{{ parseTime(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-permission="['system:dept:edit']"
                link
                type="primary"
                icon="Edit"
                @click="handleUpdate(row)"
              />
            </el-tooltip>
            <el-tooltip content="新增" placement="top">
              <el-button
                v-permission="['system:dept:add']"
                link
                type="success"
                icon="Plus"
                @click="handleAdd(row)"
              />
            </el-tooltip>
            <el-tooltip content="删除" placement="top" v-if="row.parentId != 0">
              <el-button
                v-permission="['system:dept:remove']"
                link
                type="danger"
                icon="Delete"
                @click="handleDelete(row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改部门对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" :before-close="cancel">
      <el-form ref="deptFormRef" :model="deptForm" :rules="deptFormRules" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="deptForm.parentId !== 0">
            <el-form-item label="上级部门" prop="parentId">
              <el-tree-select
                v-model="deptForm.parentId"
                :data="deptOptions"
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                value-key="id"
                placeholder="选择上级部门"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门名称" prop="deptName">
              <el-input v-model="deptForm.deptName" placeholder="请输入部门名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="deptForm.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="deptForm.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="deptForm.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="deptForm.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门状态">
              <el-radio-group v-model="deptForm.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { getDeptList, getDept, addDept, updateDept, delDept, getDeptListExcludeChild } from '@/api/system/dept'
import { parseTime } from '@/utils/global'
import DictTag from '@/components/DictTag/index.vue'

// 遮罩层
const loading = ref(true)
// 表格树数据
const deptList = ref<any[]>([])
// 部门树选项
const deptOptions = ref<any[]>([])
// 弹出层标题
const dialogTitle = ref('')
// 是否显示弹出层
const dialogVisible = ref(false)
// 是否展开，默认全部展开
const isExpandAll = ref(true)
// 重新渲染表格状态
const refreshTable = ref(true)

// 表单引用
const queryFormRef = ref<FormInstance>()
const deptFormRef = ref<FormInstance>()

// 状态数据字典
const statusOptions = ref([
  { label: '正常', value: '0', elTagType: 'primary' },
  { label: '停用', value: '1', elTagType: 'danger' },
])

// 查询参数
const queryForm = reactive({
  deptName: '',
  status: '',
})

// 部门表单数据
const deptForm = reactive({
  deptId: undefined,
  parentId: undefined,
  deptName: '',
  orderNum: 0,
  leader: '',
  phone: '',
  email: '',
  status: '0',
})

// 表单校验
const deptFormRules: FormRules = {
  parentId: [
    { required: true, message: '上级部门不能为空', trigger: 'blur' },
  ],
  deptName: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
  ],
  orderNum: [
    { required: true, message: '显示排序不能为空', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  phone: [
    { pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
}

/** 查询部门列表 */
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getDeptList(queryForm)
    deptList.value = handleTree(data, 'deptId')
  } catch (error) {
    console.error('获取部门列表失败:', error)
  } finally {
    loading.value = false
  }
}

/** 转换部门数据结构 */
const handleTree = (data: any[], id: string, parentId = 'parentId', children = 'children') => {
  const config = {
    id: id || 'id',
    parentId: parentId || 'parentId',
    childrenList: children || 'children',
  }

  const childrenListMap: any = {}
  const nodeIds: any = {}
  const tree: any[] = []

  for (const d of data) {
    const parentId = d[config.parentId]
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = []
    }
    nodeIds[d[config.id]] = d
    childrenListMap[parentId].push(d)
  }

  for (const d of data) {
    const parentId = d[config.parentId]
    if (nodeIds[parentId] == null) {
      tree.push(d)
    }
  }

  for (const t of tree) {
    adaptToChildrenList(t)
  }

  function adaptToChildrenList(o: any) {
    if (childrenListMap[o[config.id]] !== null) {
      o[config.childrenList] = childrenListMap[o[config.id]]
    }
    if (o[config.childrenList]) {
      for (const c of o[config.childrenList]) {
        adaptToChildrenList(c)
      }
    }
  }
  return tree
}

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  try {
    const { data } = await getDeptList()
    deptOptions.value = []
    const dept = { deptId: 0, deptName: '主类目', children: [] }
    dept.children = handleTree(data, 'deptId')
    deptOptions.value.push(dept)
  } catch (error) {
    console.error('获取部门树失败:', error)
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
const handleAdd = async (row?: any) => {
  reset()
  await getTreeSelect()
  
  if (row !== undefined) {
    deptForm.parentId = row.deptId
  } else {
    deptForm.parentId = 0
  }
  
  dialogVisible.value = true
  dialogTitle.value = '添加部门'
}

/** 展开/折叠操作 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
const handleUpdate = async (row: any) => {
  reset()
  await getTreeSelect()
  
  try {
    const { data } = await getDept(row.deptId)
    Object.assign(deptForm, data)
    dialogVisible.value = true
    dialogTitle.value = '修改部门'
  } catch (error) {
    console.error('获取部门信息失败:', error)
  }
}

/** 删除按钮操作 */
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `是否确认删除名称为"${row.deptName}"的数据项？`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    await delDept(row.deptId)
    await getList()
  } catch (error) {
    console.log('取消删除')
  }
}

/** 提交按钮 */
const submitForm = () => {
  deptFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (deptForm.deptId !== undefined) {
          await updateDept(deptForm)
        } else {
          await addDept(deptForm)
        }
        dialogVisible.value = false
        await getList()
      } catch (error) {
        console.error('提交部门信息失败:', error)
      }
    }
  })
}

/** 取消按钮 */
const cancel = () => {
  dialogVisible.value = false
  reset()
}

/** 表单重置 */
const reset = () => {
  Object.assign(deptForm, {
    deptId: undefined,
    parentId: undefined,
    deptName: '',
    orderNum: 0,
    leader: '',
    phone: '',
    email: '',
    status: '0',
  })
  deptFormRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.dept-management {
  padding: 20px;
}

.search-card,
.operation-card {
  margin-bottom: 20px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-operations {
  display: flex;
  gap: 8px;
}

.right-operations {
  display: flex;
  gap: 8px;
}

:deep(.el-table) {
  .el-table__cell {
    padding: 8px 0;
  }
}

.dialog-footer {
  text-align: center;
}
</style>
